package cn.scut.srp.service.impl;

import cn.scut.srp.mapper.AdminMapper;
import cn.scut.srp.mapper.OrderInfoMapper;
import cn.scut.srp.mapper.StudentMapper;
import cn.scut.srp.mapper.TeacherMapper;
import cn.scut.srp.model.BaseResponse;
import cn.scut.srp.model.ResponseCode;
import cn.scut.srp.model.entity.Administrator;
import cn.scut.srp.model.entity.Student;
import cn.scut.srp.model.entity.Teacher;
import cn.scut.srp.service.CommonService;
import cn.scut.srp.utils.JWTUtils;
import cn.scut.srp.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JWTUtils jwt;
    @Override
    public BaseResponse<ResponseCode> login(String account, String password) {
        Teacher teacher = teacherMapper.getTeacherByAccount(account);
        Student student = studentMapper.getStudentByAccount(account);
        Administrator admin = adminMapper.getAdminByAccount(account);

        if(student == null&&teacher==null&&admin==null){
            log.info("user {} not exist in database", account);
            return ResponseUtil.UserNotExist("用户不存在");
        }
        //当前登录者是学生
        if(student!=null){
            if(!student.getPassword().equals(password)){
                log.info("user {} has sent wrong password", account);
                return ResponseUtil.wrongPassword("密码错误");
            }else{
                String token = jwt.generateToken(student.getStudentAccount(),student.getStudentName(),student.getPassword());//成功了，返回token
                return ResponseUtil.OK(token);
            }
        }
        //当前登录者是教师
        if(teacher!=null){
            if(!teacher.getPassword().equals(password)){
                log.info("user {} has sent wrong password", account);
                return ResponseUtil.wrongPassword("密码错误");
            }else{
                String token = jwt.generateToken(teacher.getTeacherAccount(),teacher.getTeacherName(),teacher.getPassword());//成功了，返回token
                return ResponseUtil.OK(token);
            }
        }
        //当前登录者是管理员
        if(!admin.getPassword().equals(password)){
            log.info("user {} has sent wrong password", account);
            return ResponseUtil.wrongPassword("密码错误");
        }
        String token = jwt.generateToken(admin.getAdminAccount(),admin.getAdminName(),admin.getPassword());//成功了，返回token
        return ResponseUtil.OK(token);
    }
}
